package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.pojo.BaseAttrInfo;
import com.atguigu.gmall.product.pojo.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
* @author h8467
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2022-11-29 16:02:29
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService{

    @Autowired
    BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> getAllByCategoryId(Long c1id, Long c2id, Long c3id) {
        List<BaseAttrInfo> list = baseMapper.getAllByCategoryId(c1id,c2id,c3id);
        return list;
    }

    @Override
    public void updateAttr(BaseAttrInfo baseAttrInfo) {
        List<BaseAttrValue> oldAttrLists = baseAttrValueService.getListByAttrId(baseAttrInfo.getId());
        List<BaseAttrValue> newAttrLists = baseAttrInfo.getAttrValueList();
        ArrayList<Object> ids = new ArrayList<>();

        List<BaseAttrValue> lists = baseAttrInfo.getAttrValueList();
        lists.forEach(list->{
            list.setAttrId(baseAttrInfo.getId());
        });

        if (StringUtils.isEmpty(baseAttrInfo.getId())){

            // 如果id为空的话则新建一个
            baseMapper.insert(baseAttrInfo);
            Long id = baseAttrInfo.getId();

            // 将属性值添加到 value表中
            lists.forEach(list->{
                list.setAttrId(id);
            });
            baseAttrValueService.saveBatch(lists);

        }else {
            baseMapper.updateById(baseAttrInfo);

            // 删除
            newAttrLists.forEach(baseAttrValue -> {
                if (baseAttrValue.getId() != null){
                    ids.add(baseAttrValue.getId());

                }
            });
            LambdaQueryWrapper<BaseAttrValue> wrapper = new LambdaQueryWrapper<BaseAttrValue>().eq(BaseAttrValue::getAttrId, baseAttrInfo.getId()).notIn(BaseAttrValue::getId, ids);
            baseAttrValueService.remove(wrapper);

            // 修改和新增
            baseAttrValueService.saveOrUpdateBatch(newAttrLists);




        }
    }
}




